package xworker.swt.dataObject.datastore;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.xmeta.Thing;
import xworker.dataObject.DataStore;
import xworker.dataObject.PageInfo;

public class TableDataStoreColumn {
    TableDataStoreListener tableDataStoreListener;
    TableColumn tableColumn;
    DataStore dataStore;
    Thing attribute;

    public TableDataStoreColumn(TableDataStoreListener tableDataStoreListener, DataStore dataStore, Thing attribute){
        this.tableDataStoreListener = tableDataStoreListener;
        this.dataStore = dataStore;
        this.attribute = attribute;

        int style = SWT.NONE;
        String gridAlign = attribute.getString("gridAlign");
        if("left".equals(gridAlign)){
            style = style | SWT.LEFT;
        }else if("right".equals(gridAlign)){
            style = style | SWT.RIGHT;
        }else if("center".equals(gridAlign)){
            style = style | SWT.CENTER;
        }

        tableColumn = new TableColumn(tableDataStoreListener.table, style);
        tableColumn.setText(attribute.getMetadata().getLabel());
        int width = attribute.getInt("gridWidth");
        if(width <= 0){
            width = 80;
        }
        tableColumn.setWidth(width);
        tableColumn.setResizable(attribute.getBoolean("gridResizable"));
        tableColumn.setMoveable(true);
        tableColumn.setData("name", attribute.getMetadata().getName());

        //是否可排序
        if(attribute.getBoolean("gridSortable")){
            tableColumn.addListener(SWT.Selection, event -> {
                Table table = tableDataStoreListener.table;
                TableColumn sortColumn = table.getSortColumn();
                TableColumn currentColumn = tableColumn;
                int dir = table.getSortDirection();
                if (sortColumn == currentColumn) {
                    dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
                } else {
                    table.setSortColumn(currentColumn);
                }

                //排序的字段名
                String name = attribute.getString("name");
                PageInfo pageInfo = dataStore.getPageInfo();
                pageInfo.setSort(name);
                if(dir == SWT.DOWN){
                    pageInfo.setDir("DESC");
                }else{
                    pageInfo.setDir("ASC");
                }

                dataStore.reload();
                table.setSortDirection(dir);
            });
        }
    }

    public TableDataStoreListener getTableDataStoreListener() {
        return tableDataStoreListener;
    }

    public TableColumn getTableColumn() {
        return tableColumn;
    }

    public DataStore getDataStore() {
        return dataStore;
    }

    public Thing getAttribute() {
        return attribute;
    }
}
